# Appendix E
# Santiago Lopez-Cariboni, 2022. "Political Regimes and Informal Social Insurance", Comparative Political Studies.


# ---- wd ----
wd <- 'replication_materials' 
setwd(wd)

# ---- packages ----
pkgs <- c("data.table", "foreign", 'panelView', 'fect', "lubridate", 
    "ggplot2", "dplyr", "mFilter", "texreg", "AER", "xts", "interflex", "gridExtra")
suppressPackageStartupMessages(sapply(pkgs,require,character.only=T))
# Plot the effects (use Johannes Karreth's function: https://github.com/jkarreth/JKmisc/blob/master/ggintfun.R)
# devtools::source_url("https://raw.githubusercontent.com/jkarreth/JKmisc/master/ggintfun.R")
source('code/functions/ggintfun.R')
# Function for time Lags
source('code/functions/lagpanel.R')


# ---- data ----
dt <- fread('data/dt_replication.csv')
dt <- dt[LDC==1, ]


# ---- Table 3 ----
iv_both <- ivreg(outgap.tdl ~ l.outgap.tdl
    + l.outgap.gdp.hamilton * l.polity2
    + as.factor(iso3c)
    + as.factor(year)
    | .
    - l.outgap.gdp.hamilton*l.polity2
    + l.w.outgap.gdp.hamilton*l.wreg.polity2
    ,
    data=dt, na.action=na.omit)
summary(iv_both,  diagnostics = TRUE)
nciv_both <- length(unique(iv_both$model[['as.factor(iso3c)']]))
Fog3 <- round(summary(iv_both,  diagnostics = TRUE)$diagnostics[1,3],2)
Fdem3 <- round(summary(iv_both,  diagnostics = TRUE)$diagnostics[2,3],2)
Fint3 <- round(summary(iv_both,  diagnostics = TRUE)$diagnostics[3,3],2)

iv_both_controls <- ivreg(outgap.tdl ~ l.outgap.tdl
    + l.outgap.gdp.hamilton * l.polity2
    + l.capacity
    + l.imports
    + l.exports
    + log(l.pop)
    + log(l.gdp.pcap)
    + l.elec.cons.pc
    + l.pop.density
    + as.factor(iso3c)
    + as.factor(year)
    | .
    - l.outgap.gdp.hamilton*l.polity2
    + l.w.outgap.gdp.hamilton*l.wreg.polity2
    ,
    data=dt, na.action=na.omit)
summary(iv_both_controls,  diagnostics = TRUE)
nciv_both_controls <- length(unique(iv_both_controls$model[['as.factor(iso3c)']]))
Fog4 <- round(summary(iv_both,  diagnostics = TRUE)$diagnostics[1,3], 2)
Fdem4 <- round(summary(iv_both,  diagnostics = TRUE)$diagnostics[2,3], 2)
Fint4 <- round(summary(iv_both,  diagnostics = TRUE)$diagnostics[3,3], 2)


v.names <- c(
    "Losses Cycle$_{t-1}$",
    "GDP Output Gap$_{t-1}$",
    "polity2$_{t-1}$",
    "polity2$_{t-1}$ $\\times$ GDP Output Gap$_{t-1}$",
    "State Capacity$_{t-1}$",
    "Imports$_{t-1}$",
    "Exports$_{t-1}$",
    "Population (log)$_{t-1}$",
    "Real GDP per capita (log)$_{t-1}$",
    "Electricity Consumption$_{t-1}$",
    "Population Density$_{t-1}$"
    )


table1 <- texreg(list(iv_both,iv_both_controls),
    file= "tables/OA/T3_IV2wfe_polity2.tex",
    label="tab:polity2",
    custom.model.names = c('(1)', '(2)'),
    caption="2SLS Results: Employing the Polity 2 score",
    dcolumn = TRUE,
    no.margin=FALSE,
    fontsize="scriptsize",
    single.row=FALSE,
    use.packages=FALSE,
    booktabs = TRUE,
    digits=2,
    float.pos="htbp",
    sideways=FALSE,
    omit.coef= "(year)|(iso3c)|(Intercept)",
    include.rsquared = FALSE,
    stars = c(0.01, 0.05, 0.1),
    custom.gof.rows = list(
        "Democracy Insturment F-stat.:" = c(Fdem3, Fdem4),
        "Ouput Gap Insturment F-stat.:" = c(Fog3, Fog4),
        "Ouput Gap X Democracy Insturment F-stat.:" = c(Fint3,Fint4),
        "Year dummies" = c("Yes","Yes"), 
        "Country fixed-effects" = c("Yes", "Yes"),
        "Number of countries"= c(nciv_both,nciv_both_controls)),
    reorder.gof = c(1, 2, 3, 4, 5, 6, 8, 7),
   custom.coef.names=v.names
    )



# ---- Figure E.1 ----
Z <- c("l.outgap.tdl", "l.capacity", "l.imports", "l.exports", "l.pop", "l.gdp.pcap", "l.elec.cons.pc", "l.pop.density")
linearity_optimal <- interflex(Y = "outgap.tdl", X = "l.outgap.gdp.hamilton", D = "l.polity2", Z = Z, data = dt, estimator = "kernel", FE = c("iso3c","year"), cl = "iso3c", CI = TRUE, theme.bw = TRUE, na.rm = TRUE, bw=1) 
ylab = "Marginal Effect of Polity2 on T&D Losses"
xlab = "GDP Outpug Gap"
ylim = c(-.025, .025)
dev.off()

pdf("figures/OA/E1_linearity_polity2.pdf", width = 8, height = 6)
linearity_optimal
dev.off()
